import path from "path";
// import ejs from "ejs";
import { readFile } from "fs/promises";
export default function view({ ext, dirname }) {
  async function renderFile(filepath, data) {
    let template = await readFile(filepath, "utf8");
    let content = template.replace(/<%=(.+?)%>/g, function () {
      return data[arguments[1]];
    });
    // 将内容进行字符串拼接，并且字符串包一个with
    // 通过new  Function 字符串执行
    return content;
  }
  return async (ctx, next) => {
    ctx.render = async function (filename, data) {
      let filepath = path.join(dirname, filename + ext);
      const content = await renderFile(filepath, data);
      ctx.body = content;
    };
    return next();
  };
}
